package com.xuecheng.auth.domain.strategy;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.xuecheng.auth.domain.feginclient.CheckCodeServiceClient;
import com.xuecheng.auth.domain.model.dto.CheckCodeVerifyDto;
import com.xuecheng.auth.domain.model.dto.XcUserDto;
import com.xuecheng.auth.domain.model.entity.XcUser;
import com.xuecheng.auth.domain.model.vo.req.AuthParamsQuery;
import com.xuecheng.auth.domain.service.XcUserService;
import com.xuecheng.base.exception.XueChengPlusException;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Objects;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-09-07  15:12
 */
public class PasswordAuthStrategy implements AuthStrategy{

    @Override
    public XcUserDto execute(AuthParamsQuery params) {
        // 验证二维码
        CheckCodeServiceClient checkCodeServiceClient = SpringUtil.getBean(CheckCodeServiceClient.class);
        Boolean verify = checkCodeServiceClient.verify(new CheckCodeVerifyDto(params.getCheckcodekey(), params.getCheckcode()));
        if (!verify){
            throw new XueChengPlusException("验证码不正确");
        }
        XcUserService xcUserService = SpringUtil.getBean("xcUserServiceImpl");
        XcUser xcUser = xcUserService.getByUsername(params.getUsername());
        if (Objects.isNull(xcUser)){
            throw new XueChengPlusException("账号不存在");
        }
        PasswordEncoder passwordEncoder = SpringUtil.getBean("passwordEncoder");
        boolean matches = passwordEncoder.matches(params.getPassword(), xcUser.getPassword());
        if (!matches){
            throw new XueChengPlusException("账号或者密码不正确");
        }

        return BeanUtil.copyProperties(xcUser, XcUserDto.class);
    }
}
